<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {}
  },
  watch: {},
  created() {
    this.initSocket()
  },
  methods: {
    //app.vue
    initSocket() {
      let that = this;
      if ("WebSocket" in window) {
        console.log("您的浏览器支持 WebSocket!");
        let token = this.$store.getters.access_token;
        if (!token) {
          return;
        }
        that.ws = new WebSocket(process.env.VUE_APP_BASE_WS + '/sys/websocket/' + token);
        that.$webSocketGlobal.setWs(that.ws);
        that.ws.onopen = function (e) {
          console.log("连接打开...", e);
        };
        that.ws.onmessage = function (res) {
          console.log("收到消息", res.data)
          that.$notify.info({
            title: '收到消息',
            message: res.data
          });
        }
        //that.onopen(); 这个地方未定义是会报错，所以我写成了  that.ws.onopen = function() {console.log('开始连接')};
        that.ws.onerror = function (e) {
          console.log("连接错误...", e);
        }
        that.ws.onclose = function (e) {
          // 关闭 websocket
          console.log("连接已关闭...", e);
          setTimeout(() => {
            that.initSocket();
          }, 2000);
        };
      } else {
        // 浏览器不支持 WebSocket
        console.log("您的浏览器不支持 WebSocket!");
      }
    },


    //在其他页面发送和接收 socket 消息
    // 发送和接收消息
    handleMsg(msg) {
      let that = this;
      console.log("websocket连接信息", that.$webSocketGlobal.ws);
      if (that.$webSocketGlobal.ws && that.$webSocketGlobal.ws.readyState === 1) {
        console.log("发送信息", msg);
        that.$webSocketGlobal.ws.send(msg);
      }
      that.$webSocketGlobal.ws.onmessage = function (res) {
        console.log("收到服务器内容", res);
      };
    }

  },
  computed: {}
}
</script>
<style lang="scss">
#app {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
